//
//  AlertViewController.m
//  Fantasia
//
//  Created by kongkong on 2016/12/4.
//  Copyright © 2016年 Kongkong. All rights reserved.
//

#import "AlertViewController.h"
#import "UUDatePicker.h"
#import "AlertModel.h"
#import "AlertCell.h"

@interface AlertViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView*    tableView;
@property(nonatomic,strong) NSMutableArray<AlertModel*>*    data;
@property(nonatomic,strong) UIView*     paramsView;
@property(nonatomic,strong) UITextField*    startTime;
@property(nonatomic,strong) UITextField*    endTime;

@end

@implementation AlertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.paramsView];
    [self.view addSubview:self.tableView];
    self.title = @"报警记录";
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIView *)paramsView{
    if (!_paramsView) {
        _paramsView = [[UIView alloc]initWithFrame:CGRectMake(0, self.navigationController.navigationBar.bottom, self.view.width, 100)];
        [_paramsView addSubview:self.startTime];
        [_paramsView addSubview:self.endTime];
        UIButton* search = [[UIButton alloc]initWithFrame:CGRectMake(50, self.endTime.bottom+10, self.view.width-100, 30)];
        [search setTitle:@"搜索" forState:UIControlStateNormal];
        [search setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [search setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        [search setTitleColor:[UIColor grayColor] forState:UIControlStateSelected];
        [search setBackgroundColor:[UIColor orangeColor]];
        
        [_paramsView addSubview:search];
        
        [search addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _paramsView;
}

- (UITextField *)startTime{
    if (!_startTime) {
        _startTime = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, self.view.width/2-15, 30)];
        _startTime.borderStyle = UITextBorderStyleLine;
        _startTime.placeholder = @"起始时间";
        _startTime.inputView = [self selection:_startTime];
    }
    return _startTime;
}

- (UITextField *)endTime{
    if (!_endTime) {
        _endTime = [[UITextField alloc]initWithFrame:CGRectMake(5+self.view.width/2, 10, self.view.width/2-15, 30)];
        _endTime.borderStyle = UITextBorderStyleLine;
        _endTime.placeholder = @"结束时间";
        _endTime.inputView = [self selection:_endTime];
    }
    return _endTime;
}

- (UUDatePicker*)selection:(UITextField*)textField{
    
    return [[UUDatePicker alloc]initWithframe:CGRectMake(0, 0, 320, 200)
                           PickerStyle:UUDateStyle_YearMonthDayHourMinute
                           didSelected:^(NSString *year, NSString *month, NSString *day, NSString *hour, NSString *minute, NSString *weekDay) {
                               textField.text = [NSString stringWithFormat:@"%@-%@-%@ %@:%@",year,month,day,hour,minute];
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,  self.paramsView.bottom, self.view.width, self.view.height-self.paramsView.bottom)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[AlertCell class] forCellReuseIdentifier:@"cell"];
    }
    return _tableView;
}

- (NSString*)timeIntervalFromValue:(NSString*)value{
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyy-MM-dd HH:mm"];
    
    return [NSString stringWithFormat:@"%.0lf",[[formatter dateFromString:value] timeIntervalSince1970]];
}

- (void)searchAction{
    [self.view endEditing:YES];
    
    NSString* deviceId = [[FantasiaStorage instance]memoryValueForKey:@"currentDeviceID"];
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
    parameters[@"deviceID"] = deviceId;
    parameters[@"start"] = [self timeIntervalFromValue:self.startTime.text];
    parameters[@"end"] = [self timeIntervalFromValue:self.endTime.text];
    parameters[@"count"] = @"1000";
    parameters[@"page"] = @"0";
    
    [[[KKRequestEngine api:@"Alert" action:@"Fetch"]
      parameter:parameters]
     async:^(KKResponse*  _Nullable response, id  _Nullable result) {
         __strong typeof(weakSelf) strongSelf = weakSelf;
         if ([response isSuccess]) {
             //self.data = response.result;
             strongSelf.data = [NSMutableArray array];
             [response.originResult enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                 if ([obj isKindOfClass:[NSDictionary class]]){
                     AlertModel* model = [[AlertModel alloc]init];
                     model.alertCode = obj[@"AlertCode"];
                     model.alertTime = obj[@"AlertTime"];
                     [strongSelf.data addObject:model];
                 }
             }];
             
             [strongSelf.tableView reloadData];
         }
         else{
             [MBProgressHUD showError:response.errorMessage];
         }
     }];

}

#pragma -mark
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    AlertCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.textLabel.text = self.data[indexPath.row].alertTime;
    cell.detailTextLabel.text = self.data[indexPath.row].alertCode;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
@end
